package com.power.sifa.correction.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.plf.common.domain.PageDataResponse;
import com.plf.core.base.dao.Ha_userDao;
import com.plf.core.base.service.Ha_attachmentService;
import com.plf.core.common.service.BaseServiceImpl;
import com.power.sifa.correction.dao.Cre_warningDao;
import com.power.sifa.correction.dao.Cre_workDao;
import com.power.sifa.correction.model.Cre_work;
import com.power.sifa.correction.model.enumeration.St_work;
import com.power.sifa.correction.model.pageInfo.Cre_workPageInfo;
import com.power.sifa.correction.model.pojo.vo.RecordVo;
import com.power.sifa.correction.service.Cre_workService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.*;

/**
 * 预警处置任务业务层实现
 */
@Slf4j
@Service
public class Cre_workServiceImpl extends BaseServiceImpl implements Cre_workService {

    @Resource
    private Cre_workDao dao;
    @Resource
    private Cre_warningDao cre_warningDao;
    @Resource
    private Ha_userDao ha_userDao;
    @Resource
    private Ha_attachmentService ha_attachmentService;


    @Override
    public Cre_work getById(Serializable id) {
        return dao.findById(id).orElse(null);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveOrUpdate(Cre_work cre_work) {
        // save 如果数据库不存在这条数据，就会执行保存（即将这条数据插入到数据库）；如果数据库存在这条数据，就会根据主键去更新这条数据
        if (cre_work.getPrimaryKey() != null) {
            Cre_work cre_workfDb = dao.findById(cre_work.getPrimaryKey()).orElse(null);
            if (cre_workfDb != null) {
                BeanUtils.copyProperties(cre_work, cre_workfDb);
                dao.save(cre_workfDb);
                return;
            }
        }
        dao.save(cre_work);
    }

    @Override
    public void removeById(Serializable id) {
        dao.deleteById(id);
    }

    @Override
    public Page<Cre_work> findAll(Cre_workPageInfo pageInfo) {
        //排序等定义
        Sort sort;
        if ("asc".equals(pageInfo.getOrder())) {
            sort = Sort.by(Sort.Direction.ASC, pageInfo.getSort());
        } else {
            sort = Sort.by(Sort.Direction.DESC, pageInfo.getSort());
        }
        //分页的定义
        Pageable pageable = PageRequest.of(pageInfo.getPageNumber() <= 1 ? 0 : pageInfo.getPageNumber() - 1, pageInfo.getPageSize(), sort);
        //查询条件
        Specification spec = this.createSpecification(pageInfo);
        return dao.findAll(spec, pageable);
    }

    @Transactional(rollbackFor = Exception.class)
    public void removeByIds(List<Integer> ids) {
        dao.removeByIds(ids);
    }

    @Override
    public List<Cre_work> findAll() {
        return dao.findAll();
    }

    @Override
    public void saveAll(List<Cre_work> list) {
        dao.saveAll(list);
    }

    @Override
    public PageDataResponse queryList(Cre_workPageInfo pageInfo) {
        List<Cre_work> list = this.dao.queryList(pageInfo);
        // 分页
        PageDataResponse page = new PageDataResponse();
        if (CollectionUtil.isNotEmpty(list)) {
            Long total = Long.valueOf(pageInfo.getAllcount());
            int size = pageInfo.getPageSize() * pageInfo.getPageNumber();
            if (total.intValue() - size > 0) {
                page.setNextPage(pageInfo.getPageNumber() + 1);
            }
            page.setSize(pageInfo.getPageSize());
            page.setCurrent(pageInfo.getPageNumber());
            page.setTotal(total);
        } else {
            page.setSize(0);
            page.setCurrent(1);
            page.setTotal(0L);
        }
        page.setRecords(list);
        return page;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateWorktype(String workid, String warnid, Integer worktype) {
        this.dao.updateWorktype(workid, worktype);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateStatus(String id, Integer status) {
        this.dao.updateStatus(id, status);
    }

    @Override
    public void updateStatus(String id, Integer status, Date exectime) {
        this.dao.updateStatus(id, status, exectime);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void setSupid(String id, String supid) {
        this.dao.setSupid(id, supid);
    }

    @Override
    public void repeatSave(Cre_work work) {
        // 1. 查询人所在单位
        List<Map> userList = this.ha_userDao.findUserDeptsByUserid(work.getUserid());
        if (CollectionUtils.isEmpty(userList)) {
            log.error("根据录入人id查询信息失败");
            throw new RuntimeException("根据录入人id查询信息失败");
        }
        Map userObj = userList.get(0);
        work.setCreatetime(new Date());
        work.setDeptid((String) userObj.get("sectionid"));
        work.setDeptname((String) userObj.get("sectionname"));
        dao.save(work);
    }

    @Override
    public Map<String, Integer> getDisposalStatus(List f_deptid) {
        Map<String, Integer> result = new HashMap<>();
        result.put("pending", 0);
        result.put("disposed", 0);
        Map<Integer, Integer> map = this.dao.getDisposalStatus(f_deptid);
        log.info("返回的结果:{}", map);
        if (map != null) {
            map.keySet().forEach(key -> {
                switch (key) {
                    case St_work.DONE:
                        result.put("disposed", result.get("disposed") + map.get(key));
                        break;
                    case St_work.UNDO:
                    case St_work.DOING:
                        result.put("pending", result.get("pending") + map.get(key));
                        break;
                    default:
                        break;
                }
            });
        }
        return result;
    }

    @Override
    public List<RecordVo> findProcess(String warnId) {
        List<RecordVo> recordVo = dao.findProcess(warnId);
//        for (RecordVo vo : recordVo) {
//            if (ObjectUtil.isNull(vo.getFileids())) {
//                continue;
//            }
//            vo.setFileids(ha_attachmentService.getFileUrl());
//        }
        return recordVo;
    }

}
